package com.gift.recommendation.modules.login.biz;

import com.gift.recommendation.config.GiftProperties;
import com.gift.recommendation.config.TokenConfig;
import com.gift.recommendation.modules.login.dto.EmailEntityExt;
import com.gift.recommendation.modules.login.dao.entity.UserEntity;
import com.gift.recommendation.modules.login.dto.*;
import com.gift.recommendation.modules.login.service.LoginService;
import com.gift.recommendation.util.SendEmail;
import com.gift.recommendation.util.SendVerificationCode;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.text.Collator;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author zzh <2658137258@qq.com>
 * @date 2022/11/4
 */
@Service
public class LoginImpl {
    @Autowired
    private LoginService loginService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SendEmail sendEmail;

    @Autowired
    private GiftProperties giftProperties;

    /**
     * 用户登录接口
     * @param req
     * @return
     */
    public UserLoginRsp userLogin(UserLoginReq req) {
        Example example = new Example(UserEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("email",req.getEmail());
        criteria.andEqualTo("password",req.getPassword());
        List<UserEntity> userEntityList = loginService.selectByExample(example);
        UserEntity userEntity = new UserEntity();
        if (CollectionUtils.isEmpty(userEntityList)) {
            throw new RuntimeException("用户名密码错误");
        } else {
            userEntity = userEntityList.get(0);
        }

        String token = TokenConfig.createToken(userEntity.getUuid());
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowDate = format.format(date);
        UserLoginRsp userLoginRsp = new UserLoginRsp();
        userLoginRsp.setUserName(userEntity.getName());
        userLoginRsp.setLoginDate(nowDate);
        userLoginRsp.setUserJurisdiction(userEntity.getType());
        userLoginRsp.setToken(token);
        userLoginRsp.setUserUuid(userEntity.getUuid());
        return userLoginRsp;
    }

    public void sendEmail(SendEmailReq req) {
        String verification = SendVerificationCode.getVerificationCode();
        redisTemplate.opsForValue().set(req.getEmail(),verification,giftProperties.getOverTime(),TimeUnit.MINUTES);
        EmailEntityExt emailEntity = new EmailEntityExt();
        emailEntity.setEmail(req.getEmail());
        String data = "【礼物赠送系统】验证码：" + verification + ", 您正在使用邮箱注册礼物赠送系统\n"
                + "验证码有效期为" + giftProperties.getOverTime() + "分钟（若非本人操作,请删除此邮件）";
        emailEntity.setData(data);
        sendEmail.sendEmails(emailEntity);
    }

    public void userRegister(UserRegisterReq req) {
        String verification = redisTemplate.opsForValue().get(req.getEmail());
        if(StringUtils.isBlank(verification)){
            throw new RuntimeException("验证码已过期");
        }
        if(!verification.equals(req.getVerificationCode())){
            throw new RuntimeException("验证码错误");
        }
        Example example = new Example(UserEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("email",req.getEmail());
        List<UserEntity> list = loginService.selectByExample(example);
        if (CollectionUtils.isNotEmpty(list)) {
            throw new RuntimeException("此邮箱已注册");
        }
        UserEntity userEntity = new UserEntity();
        userEntity.setUuid(UUID.randomUUID().toString());
        userEntity.setEmail(req.getEmail());
        userEntity.setName(req.getName());
        userEntity.setPassword(req.getPassword());
        userEntity.setType(2);
        loginService.insertSelective(userEntity);
    }
}
